package com.yunquan.ohana.ui.photos

import android.app.Application
import android.content.Context
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewModelScope
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.bus.event.SingleLiveEvent
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.entity.PhotoGroupEntity
import com.yunquan.ohana.entity.PhotosEntity
import com.yunquan.ohana.ui.photos.item.PhotosItemViewModel
import com.yunquan.ohana.utils.L
import com.yunquan.ohana.utils.MediaUtils
import com.yunquan.ohana.utils.Utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.tatarka.bindingcollectionadapter2.ItemBinding

class PhotosViewModel(application: Application) : BaseViewModel(application) {

    val ui = SingleLiveEvent<Int>()

    // 是否单选
    val isSingleSelect = ObservableField(false)

    // 显示类型 0不限制，1图片，2视频
    val showType = ObservableField(0)

    // 分割线宽
    val lineWidth = ObservableField<Int>()

    // 当前组名
    val groupName = ObservableField<String>("Recents")

    // 组列表
    val groupList = mutableListOf<PhotoGroupEntity>()

    // Items数据
    val items = ObservableArrayList<PhotosItemViewModel>()
    val itemBinding = ItemBinding.of<PhotosItemViewModel>(BR.photosItemViewModel, R.layout.item_photos)

    // 当前选择列表
    val checkedList = mutableMapOf<Long, PhotosEntity>()

    // 当前选择的是否是同一类，不是则显示错误提示
    val showError = ObservableField(false)
    val errorTip = ObservableField<String>()

    // 当前选择的Item
    var mCurrentItem: PhotosItemViewModel? = null
    var mPage: Int = 0

    val onGroupClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            ui.value = 0
        }
    })

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        lineWidth.set(Utils.instance.dp2px(7f))
    }

    // Item单机处理
    fun onItemClick(itemViewModel: PhotosItemViewModel) {
        if (itemViewModel.data == null) {
            ui.value = 1
        } else {
            mCurrentItem = itemViewModel
            ui.value = 2
        }
    }

    // Item选择状态处理
    fun onCheckChange(b: Boolean, data: PhotosEntity): Boolean {
        val result = if (b) {
            checkedList[data.id!!] = data
            true
        } else {
            checkedList.remove(data.id)
            false
        }
        errorTip()
        return result
    }

    // 判断是否需要显示错误提示
    fun errorTip() {
        if (checkedList.isEmpty()) {
            errorTip.set("")
            showError.set(false)
            return
        }
        val where = checkedList.values.map {
            if (it.type?.contains("image") == true) 1 else 2
        }.distinct().size != 1
        val isSame = if (!where) {
            val data = checkedList.values.first()
            if (data.type!!.contains("image")) {
                if (checkedList.size > 9) {
                    errorTip.set(Utils.instance.getString(R.string.tip_photos_selected_image_number))
                    true
                } else {
                    errorTip.set("")
                    false
                }
            } else {
                if (checkedList.size > 1) {
                    errorTip.set(Utils.instance.getString(R.string.tip_photos_selected_video_number))
                    true
                } else {
                    errorTip.set("")
                    false
                }
            }
        } else {
            errorTip.set(Utils.instance.getString(R.string.tip_photos_selected_image_and_video))
            true
        }
        showError.set(isSame)
    }

    fun loadAllAlbumData(context: Context) {
        viewModelScope.launch(Dispatchers.IO) {
            val list = if (groupName.get() == "Recents") {
                MediaUtils.page(context, null, mPage, 40)
            } else {
                MediaUtils.page(context, groupName.get(), mPage, 40)
            }

            withContext(Dispatchers.Main) {
                if (mPage == 0) {
                    items.clear()
                    items.add(PhotosItemViewModel(this@PhotosViewModel))
                }
                items.addAll(list.map { PhotosItemViewModel(this@PhotosViewModel, it) })
                ui.value = 3
            }
        }
    }

    fun loadAllAlbumGroup(context: Context) {
        viewModelScope.launch(Dispatchers.IO) {
            val allCount = MediaUtils.getAllCount(context)
            val allList = MediaUtils.getAllGroup(context)
            groupList.clear()
            groupList.add(PhotoGroupEntity("Recents", allCount))
            for (e in allList) {
                val count = MediaUtils.getGroupCount(context, e)
                groupList.add(PhotoGroupEntity(e, count))
            }
        }
    }
}